package com.pig4cloud.pig.mt.controller;

import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.mt.entity.WxUser;
import com.pig4cloud.pig.mt.form.WxUserTaggingForm;
import com.pig4cloud.pig.mt.service.WxUserService;
import com.pig4cloud.pig.mt.service.WxUserTagsService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/wxUserTags")
@RequiredArgsConstructor
@Api(value = "wxUserTags", tags = "用户标签管理")
public class WxUserTagsController {
	@Autowired
	WxUserTagsService wxUserTagsService;
	@Autowired
	WxUserService wxUserService;
	private final WxMpService wxMpService;

	@GetMapping("/userTags")
	public R userTags(@CookieValue String appid, @CookieValue String openid){
		if(openid==null){
			return R.failed("none_openid");
		}
		this.wxMpService.switchoverTo(appid);
		WxUser wxUser = wxUserService.getById(openid);
		if(wxUser==null){
			wxUser=wxUserService.refreshUserInfo(openid,appid);
			if(wxUser==null) {
				return R.failed("not_subscribed");
			}
		}
		return R.ok(wxUser.getTagidList());
	}

	@PostMapping("/tagging")
	public R tagging(@CookieValue String appid,@CookieValue String openid , @RequestBody WxUserTaggingForm form) {
		this.wxMpService.switchoverTo(appid);
		try {
			wxUserTagsService.tagging(form.getTagid(), openid);
		} catch (WxErrorException e) {
			WxError error = e.getError();
			if (50005 == error.getErrorCode()) {//未关注公众号
				return R.failed("not_subscribed");
			} else {
				return R.failed(error.getErrorMsg());
			}
		}
		return R.ok();
	}

	@PostMapping("/untagging")
	public R untagging(@CookieValue String appid,@CookieValue String openid , @RequestBody WxUserTaggingForm form) throws WxErrorException {
		this.wxMpService.switchoverTo(appid);
		wxUserTagsService.untagging(form.getTagid(), openid);
		return R.ok();
	}
}
